package main

import (
	"bytes"
	"github.com/dchest/captcha"
	"github.com/gin-contrib/sessions"
	"github.com/gin-contrib/sessions/cookie"
	"github.com/gin-gonic/gin"
	"net/http"
	"time"
)

func Secssioncofig() sessions.Store {
	sessionMaxAge  :=   3600
	seessionSecret := "golang-tech-stack"
	store := cookie.NewStore([]byte(seessionSecret))
	store.Options(sessions.Options{
		MaxAge: sessionMaxAge,//seconds
		Path: "/",
	})
return store
	
}
//中间件，处理session
func Session(Keypairs string) gin.HandlerFunc {
	store := Secssioncofig()
	return sessions.Sessions(Keypairs, store)
}
//生成验证码
func Captcha(c *gin.Context, length ...int) {
	l := captcha.DefaultLen
	w,h :=107,36
	if len(length) == 1 {
			l = length[0]
		}

	if len(length) == 2 {
		w = length[1]
	}
		if len(length) ==3 {
			h = length[2]
		}
		capchaId := captcha.NewLen(l)
		session := sessions.Default(c)
		session.Set("captcha",capchaId)
		_= session.Save()
		_= Serve(c.Writer,c.Request, capchaId,".png","zh",false,w,h)
	}

//验证
func CaptchaVerify(c *gin.Context, code string) bool {
	session :=sessions.Default(c)
	if captchaId := session.Get("captcha"); captchaId != nil {
		session.Delete("captcha")
		_= session.Save()
		if captcha.VerifyString(captchaId.(string), code) {
                return true
		}else {
			    return false
		}
	}else{
		  return false
	}
}
//生成图片
func Serve(w http.ResponseWriter, r *http.Request, id, ext, lang string, download bool,width, height int)(error)  {
	w.Header().Set("Cache-Control", "no-cache, no-stroe, must-revalidate")
	w.Header().Set("Pragma", "no-cache")
	w.Header().Set("Expires","0")
	var content bytes.Buffer
	switch ext {
	case ".png":
		w.Header().Set("Content-Type", "image/png")
		_= captcha.WriteImage(&content, id, width, height)
	case ".wav":
		w.Header().Set("Content-Type", "audio/x-wav")
	default:
		return captcha.ErrNotFound

	}
	if download {
		w.Header().Set("Content-Type", "application/octet-stream")
	}
	http.ServeContent(w,r, id+ext,time.Time{},bytes.NewReader(content.Bytes()))
	return nil
}
func main()  {
	router := gin.Default()
	router.LoadHTMLGlob("./*.html")
	router.Use(Session("golang-tech-stack"))
	router.GET("/captcha", func(c *gin.Context) {
		value := c.PostForm("code")
		if CaptchaVerify(c, value) {
			     c.JSON(http.StatusOK, gin.H{"status": 0, "msg": "success"})
		} else {
			     c.JSON(http.StatusOK, gin.H{"status": 1, "msg": "failed"})
		}
	})

	router.Run(":9090")
	// http://locahost:8080/

}